package com.senmo.activity.common;

import android.os.Bundle;

import com.senmo.activity.main.MainActivity;
import com.senmo.activity.user.LoginActivity;
import com.senmo.base.BaseActivity;
import com.senmo.manager.AccountManager;
import com.senmo.manager.UserCallback;
import com.senmo.model.User;
import com.senmo.request.DataHull;
import com.senmo.senmo.R;

import lx.af.manager.GlobalThreadManager;

/**
 * author: lx
 * date: 16-1-5
 */
public class SplashActivity extends BaseActivity {

    private static final long MIN_SHOW_TIME = 3000;

    private long mStartTime = System.currentTimeMillis();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        AccountManager.getInstance().autoLogin(new UserCallback() {
            @Override
            public void onSuccess(User user) {
                startNextDelayed(true);
            }

            @Override
            public void onFail(int error, DataHull datahull) {
                startNextDelayed(false);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void startNextDelayed(final boolean loginSuccess) {
        long current = System.currentTimeMillis();
        long delta = current - mStartTime;
        if (delta >= MIN_SHOW_TIME) {
            startNext(loginSuccess);
        } else {
            GlobalThreadManager.runInUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    startNext(loginSuccess);
                }
            }, MIN_SHOW_TIME - delta);
        }
    }

    private void startNext(boolean loginSuccess) {
        if (loginSuccess) {
            startActivity(MainActivity.class);
        } else {
            startActivity(LoginActivity.class);
        }
        finish();
    }

}
